import React, { useState, useEffect } from 'react'
import { Form, Descriptions, Row, Button, Input, Table } from 'antd'
import { departmentRule } from "@/utils/rules";
import { useDispatch, useSelector } from "umi"
import DrowPover from "@/components/DropPopover";
import ChildDepart from "../ChildDepart";
import { detailColumns } from '../departColumns';
import $http from "@/services";
import "./index.less"


export default function index({ setShowModal, modalType }) {
  const [form] = Form.useForm();
  const [childList, setChildList] = useState([]);
  const dispatch = useDispatch();
  const { departmentDetail } = useSelector(state => state.department);
  console.log(departmentDetail)

  // 设置传过来的值
  const getNewValue = (newValue) => {
    form.setFieldsValue({
      departmentLeaderName: newValue.userName,
      departmentLeader: newValue._id
    });
    // 只有为更新的时候才进行处理
    modalType === 'update' && updateCheck({
      type: "departmentLeader"
    })
  }

  // 提交进行修改或者删除
  const pushOrUpdateList = ({ list, type, isDelete = false }) => {
    // 若为创建消除其ids则直接删除其childList
    if (type === 'add') {
      if (isDelete) {
        list = childList.map(el => {
          const isReturn = list.every(delItem => delItem._id !== el._id)
          if (isReturn) {
            return el;
          }
        })
        list = list.filter(el => el);
      }
      setChildList(list);
    } else if (type === "update") {
      // 当为更新其update时 如加入其内容时则使用update
      const updateChildListData = [...departmentDetail?.children, ...list]
      const updataVal = updateChildListData.map(el => el._id);
      setChildList(updateChildListData);
      updateCheck({ type: "children", data: updataVal })
    } else {
      // 更新且删除时执行这个
      const updataVal = list.map(el => el._id);
      updateCheck({ type: "children", data: updataVal, isDelete: type === 'del' })
    }
  }

  // 创建子部门
  const handleAddFinsh = (data) => {
    const value = form.getFieldValue("departmentLeader");
    data = {
      ...data,
      departmentLeader: value,
      children: childList
    }
    delete data.departmentLeaderName;
    dispatch({
      type: "department/addDepartmentList",
      payload: data
    });
    setShowModal(false)
  }

  // 更新数据检验
  const updateCheck = ({ type, isDelete = false, data }) => {
    const updateValue = type === "children" ? data : form.getFieldValue(type);
    let oldDateValue;
    if (type === "departmentLeader") {
      oldDateValue = departmentDetail[type]._id;
    } else {
      oldDateValue = departmentDetail[type];
    }
    // 若相同则不进行处理
    if (oldDateValue === updateValue) return;
    console.log(updateValue, type)
    updataInputValue(type, isDelete, updateValue);
  }
  // 更新处理的值
  const updataInputValue = (type, isDelete, updateVal) => {
    dispatch({
      type: "department/updateDepartmentDetail",
      payload: {
        type,
        isDelete,
        updateVal,
        _id: departmentDetail?._id
      }
    })
  }

  return (
    <Form
      form={form}
      onFinish={handleAddFinsh}
      initialValues={{
        departmentName: departmentDetail?.departmentName,
        remark: departmentDetail?.remark,
        departmentLeader: departmentDetail?.departmentLeader?._id,
        departmentLeaderName: departmentDetail?.departmentLeader?.userName
      }
      }
    >
      <Descriptions bordered column={1} labelStyle={{ width: '150px' }}>
        <Descriptions.Item label="部门名称" layout="vertical">
          <Form.Item
            rules={departmentRule.departmentName}
            name="departmentName"
          >
            <Input placeholder='请输入部门名称' onBlur={() => modalType === 'update' && updateCheck({ type: "departmentName" })} style={{ border: "1px solid #ccc" }}></Input>
          </Form.Item>
        </Descriptions.Item>
        <Descriptions.Item label="备注">
          <Form.Item name="remark" >
            <Input placeholder='请输入部门相关备注' onBlur={() => modalType === 'update' && updateCheck({ type: "remark" })} style={{ border: "1px solid #ccc" }}></Input>
          </Form.Item>
        </Descriptions.Item>
        <Descriptions.Item label="子部门">
          <ChildDepart
            pushOrUpdateList={pushOrUpdateList}
            modalType={modalType}
            childList={modalType === 'update' ? departmentDetail?.children : childList}></ChildDepart>
        </Descriptions.Item>
        <Descriptions.Item label="部门负责人">
          <Form.Item name="departmentLeaderName" rules={departmentRule.departmentLeader}>
            <Input
              readOnly
              placeholder="请输入部门的负责人"
              className='border-1'
              addonAfter={<DrowPover
                placeValue={"请输入查找的员工姓名"}
                searchType={'userName'}
                getnewValue={getNewValue}
                interfaced={"getStaffLists"}></DrowPover>}></Input>
          </Form.Item>
        </Descriptions.Item>
        {modalType === 'update' && <Descriptions.Item label="部门人员">
          <Table
            className='department-container'
            pagination={false}
            rowKey={el => el?._id}
            dataSource={departmentDetail?.staffList ? departmentDetail?.staffList : []
            } columns={detailColumns}>
          </Table>

        </Descriptions.Item>}
      </Descriptions>
      {modalType === 'add' && <Form.Item>
        <Row justify={"end"}>
          <Button type='primary' htmlType='submin'>创建</Button>
        </Row>
      </Form.Item>}
    </Form>
  )
}
